const Promise = require('./Promise') 
let wcache = require('./wcache.js')

function login() {
  return new Promise((resolve, reject) => wx.login({
    success: resolve,
    fail: reject
  }))
}

function getUserInfo() {
  return login().then(res => new Promise((resolve, reject) =>
    wx.getUserInfo({
      success: resolve,
      fail: reject
    })
  ))
}

function requstGet(url, data) {
  return requst(url, 'GET', false, false, data)
}


function requstGetShowLoading(url, data) {
  return requst(url, 'GET',true,false,data)
}

function requstPostJsonShowLoading(url, data) {
  return requst(url, 'POST', true,true, data)
}

function requstPostJson(url, data) {
  return requst(url, 'POST', false, true,data)
}

function requstPostShowLoading(url, data) {
  return requst(url, 'POST', true, false,json2Form(data))
}


function requstPost(url, data) {
  return requst(url, 'POST', false, false,json2Form(data))
}

// 小程序上线需要https，这里使用服务器端脚本转发请求为https
function requst(url, method,isShowLoading,isJsonHeader,data = {}) {
  var session_id = wx.getStorageSync('SESSID');//本地取存储的sessionID
  let token = wcache.get('loginToken',"");
  if (session_id != "" && session_id != null) {
    var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': "JSESSIONID=" + session_id, "token": token, "acceptType": "xcx"}
  } else {
    if (isJsonHeader){
      var header = { 'content-type': 'application/json;charset=utf-8', "token": token, "acceptType":"xcx"}
    }else{
      var header = { 'content-type': 'application/x-www-form-urlencoded', "token": token, "acceptType": "xcx"}
    }
  }

  wx.showNavigationBarLoading()
  if (isShowLoading)
    wx.showLoading({title: '请稍等',})
  return new Promise((resove, reject) => {
    wx.request({
      url: url,
      data: data,
      header: header,
      method: method.toUpperCase(), // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function (res) {
        wx.hideNavigationBarLoading()
        if (isShowLoading)
           wx.hideLoading();
        if (res.data.code == '03'){
            wx.redirectTo({
              url: '../login/login?type=1',
            })
        }else{
          resove(res.data);
        }
        console.log(res.data)
      },
      fail: function (msg) {
        wx.hideNavigationBarLoading()
        if (isShowLoading)
           wx.hideLoading();
        reject('fail')
      }
    })
  })
}

function json2Form(json) {
  var str = [];
  for (var p in json) {
    if (typeof json[p] === "string") {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
    } else {
      str.push(encodeURIComponent(p) + "=" + JSON.stringify(json[p]));
    }
  }
  return str.join("&");
}

module.exports = {
  login,
  getUserInfo, Promise, requst,
  get: requstGet, 
  post: requstPost,
  getLoading: requstGetShowLoading,
  postLoading: requstPostShowLoading,
  postJsonLoading: requstPostJsonShowLoading,
  postJson: requstPostJson
}